package com.kingwang.training.designpattern.interpreter.bo;

import java.util.Map;
import java.util.Stack;

/**
 * @author King
 */
public class Calculator {
    private Expression expression;

    public Calculator(String expressionStr) {
        // 构造表达式
        Stack<Expression> stack = new Stack<>();

        // 只支持单字符变量
        char[] expressionArray = expressionStr.replace(" ", "").toCharArray();

        Expression left;
        Expression right;

        for (int i = 0; i < expressionArray.length; i++) {
            char c = expressionArray[i];
            // 1. a+b
            // 2. (a+b)+c
            // 3. ((a+b)+c)-d
            // 4. (((a+b)+c)-d)+e
            switch (c) {
                case '+':
                    left = stack.pop();
                    right = new VariableExpression(String.valueOf(expressionArray[++i]));
                    stack.push(new AddExpression(left, right));
                    break;
                case '-':
                    left = stack.pop();
                    right = new VariableExpression(String.valueOf(expressionArray[++i]));
                    stack.push(new SubExpression(left, right));
                    break;
                default:
                    stack.push(new VariableExpression(String.valueOf(c)));
                    break;
            }
        }

        this.expression = stack.pop();
    }

    /**
     * 计算结果
     *
     * @param variables
     * @return
     */
    public Double calculate(Map<String, Double> variables) {
        // 1. (((a+b)+c)-d)+e.value
        // 2. ((a+b)+c)-d.value+e.value
        return this.expression.interpret(variables);
    }
}
